package com.kui.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.kui.exception.BusinessException;
import com.kui.exception.ErrorCode;
import com.kui.exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class PictureUpload extends FileUploadTemplate {
    @Override
    protected void processFile(Object inputSource, File file){
        MultipartFile multipartFile = (MultipartFile) inputSource;
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件上传失败");
        }
    }

    @Override
    protected String getOriginalFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    protected void validPicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        // 1.校验图片是否存在
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "图片不存在");
        // 2.校验图片大小
        long multipartFileSize = multipartFile.getSize();
        // 定义1MB大小的常量
        final long maxFileSize = 1024 * 1024;
        ThrowUtils.throwIf(multipartFileSize > 5 * maxFileSize, ErrorCode.PARAMS_ERROR, "图片大小不能超过5MB");
        // 3.校验图片格式
        // 拿到文件的后缀
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 定义允许上传的后缀列表
        final List<String> allowSuffix = Arrays.asList("png", "jpg", "jpeg", "bmp", "gif", "webp");
        ThrowUtils.throwIf(!allowSuffix.contains(suffix), ErrorCode.PARAMS_ERROR, "图片格式不支持");
    }
}
